<?php
declare (strict_types = 1);

namespace app\middleware;

use app\model\Meituan;
use app\model\MeituanCity;

class MeituanCityNameToCityId
{

    const MEITUAN_DDEFAULT_CITYID = 1;
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     */
    public function handle($request, \Closure $next)
    {
        $cityName = input('cityName','');

        if (empty($cityName)){
            $request->cityId = self::MEITUAN_DDEFAULT_CITYID;//默认厦门
            return  $next($request);
        }

        $cityName = str_replace('市','',$cityName);

        $meituanCityName =MeituanCity::where('name',$cityName)
            ->where('city_id','<>',0)
            ->cache('meituancitySearch'.$cityName,120)
            ->find();

        if (!$meituanCityName){
            $request->cityId = self::MEITUAN_DDEFAULT_CITYID;
            return  $next($request);
        }

        $request->cityId = $meituanCityName->city_id;

        return  $next($request);
    }
}
